import java.util.ArrayList;
import java.util.List;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class pathSum {
    public List<List<Integer>> _pathSum(TreeNode root, int target) {
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, target, path, res);
        return res;
    }

    private void dfs(TreeNode node, int target, List<Integer> path, List<List<Integer>> res) {
        // 中止条件
        if (node == null)
            return;
        path.add(node.val);
        target -= node.val;
        // 判断是否可以添加
        if (target == 0 && node.left == null && node.right == null) {
            res.add(new ArrayList<>(path));
        }

        dfs(node.left, target, path, res);
        dfs(node.right, target, path, res);
        path.remove(path.size() - 1);
    }

    public static void main(String[] args) {
        pathSum test = new pathSum();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        System.out.println(test._pathSum(root, 8));
    }
}
